package com.kezesong.leasing.common;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.kezesong.leasing.dto.SessionInfo;
import com.kezesong.leasing.entity.UserInfoEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CacheService {
    static Logger logger = LoggerFactory.getLogger(CacheService.class);
    private static final LoadingCache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(1000) // 最大缓存数目
            .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
            .build(new CacheLoader<String, String>() {
                // 默认的数据加载方式
                @Override
                public String load(String key) throws Exception {
                    return null;
                }
            });

    public static SessionInfo getUserLoginInfo(String sessionId) throws ExecutionException {
        if (StringUtils.isNotBlank(sessionId)){
            String userInfoJson = cache.get(sessionId);
            if (StringUtils.isNotBlank(userInfoJson)){
                return JSON.parseObject(userInfoJson,SessionInfo.class);
            }
        }
        return null;
    }

    public static String createLoginSesssion(SessionInfo sessionInfo){
        String sessionId = sessionInfo.getOpenId();
        String sessionInfoJson = JSON.toJSONString(sessionInfo);
        cache.put(sessionId, sessionInfoJson);
        logger.debug("============================CacheService.createLoginSesssion sessionId:{}, useInfoJson:{}",sessionId,sessionInfoJson);

        return sessionId;
    }
}
